package com.javer.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.springframework.util.Assert;

import com.javer.domain.Comment;
import com.javer.domain.PageView;

public abstract class WebUtil {
	private static Pattern pattern = Pattern.compile("\\[(\\d+)\\]");

	public static PageView createPageView(HttpServletRequest req) {
		int pageSize = PageView.PAGE_SIZE;
		int pageNo = 1;
		
		if (req.getParameter("pageSize") != null) {
			pageSize = Integer.valueOf(req.getParameter("pageSize"));
		}
		
		if (req.getParameter("pageNo") != null) {
			pageNo = Integer.valueOf(req.getParameter("pageNo"));
		}
		
		PageView pv = new PageView(pageNo, pageSize);
		return pv;
	}
	
	
	/**
	 * 处理评论内容，主要包括去掉标签和替换QQ表情
	 * @param comment
	 */
	public static void handleCommentContent(Comment comment) {
		Assert.notNull(comment);
		String content = comment.getContent();
		content = WebUtil.escapeHtml(content);
		content = WebUtil.replaceFaceImage(content);
		comment.setContent(content);
	}
	
	public static String replaceFaceImage(String html) {
		Matcher matcher = pattern.matcher(html);
		while (matcher.find()) {
			html = matcher.replaceFirst("<img src=\"images/faces/"+ matcher.group(1) +".gif\">");
			matcher = pattern.matcher(html);
		}
		return html;
	}
	
	public static String escapeHtml(String html) {
		Assert.notNull(html);
		return html.replaceAll("<[^<>]*>", "");
	}
}
